import { View, Text, ScrollView } from '@tarojs/components'
import { Popup } from '@nutui/nutui-react-taro'
import { Close } from '@nutui/icons-react-taro'
import React from 'react'
import './index.less'

export interface SelectorOption {
  /** 选项ID */
  id: string
  /** 选项名称 */
  name: string
  /** 选项描述 */
  description?: string
  /** 选项图片 */
  image?: string
  /** 选项额外信息 */
  extra?: React.ReactNode
  /** 自定义数据 */
  [key: string]: any
}

export interface ModalSelectorProps<T = SelectorOption> {
  /** 是否显示 */
  visible: boolean
  /** 标题 */
  title: string
  /** 选项列表 */
  options: T[]
  /** 当前选中的ID */
  selectedId?: string
  /** 选择事件 */
  onSelect: (option: T) => void
  /** 关闭事件 */
  onClose: () => void
  /** 是否显示图片 */
  showImage?: boolean
  /** 自定义渲染选项 */
  renderOption?: (option: T, isSelected: boolean) => React.ReactNode
  /** 自定义类名 */
  className?: string
}

/**
 * ModalSelector 模态选择器组件
 * 通用的模态选择器，支持图片、描述等多种展示形式
 */
function ModalSelector<T extends SelectorOption = SelectorOption>({
  visible,
  title,
  options,
  selectedId,
  onSelect,
  onClose,
  showImage = true,
  renderOption,
  className = '',
}: ModalSelectorProps<T>) {
  const handleSelect = (option: T) => {
    onSelect(option)
    onClose()
  }

  const renderDefaultOption = (option: T, isSelected: boolean) => (
    <View
      key={option.id}
      className={`selector-option ${isSelected ? 'selected' : ''}`}
      onClick={() => handleSelect(option)}>
      {showImage && option.image && (
        <View className='option-image'>
          <image src={option.image} mode='aspectFill' className='image' />
        </View>
      )}
      <View className='option-content'>
        <Text className='option-name'>{option.name}</Text>
        {option.description && <Text className='option-description'>{option.description}</Text>}
        {option.extra && <View className='option-extra'>{option.extra}</View>}
      </View>
      {isSelected && <View className='selected-badge'>✓</View>}
    </View>
  )

  return (
    <Popup visible={visible} position='bottom' onClose={onClose} className={`modal-selector ${className}`}>
      <View className='selector-header'>
        <Text className='selector-title'>{title}</Text>
        <Close size={20} onClick={onClose} className='close-icon' />
      </View>
      <ScrollView scrollY className='selector-content'>
        {options.map((option) => {
          const isSelected = option.id === selectedId
          return renderOption ? renderOption(option, isSelected) : renderDefaultOption(option, isSelected)
        })}
      </ScrollView>
    </Popup>
  )
}

export default ModalSelector

